import func from "_u/func"

const state = {
  questionList: [],
  questionNum: 0,
  collectList: [],
}

const mutations = {
  ["SET_QUESTION_LIST"](state, data) {
    state.questionList = data
  },
  ["SET_COLLECT_LIST"](state, data) {
    state.collectList = data
  },
  ["SET_QUESTION_NUM"](state, data) {
    state.questionNum = data
  },
}

const getters = {
  questionList: (state) => {
    return state.questionList
  },
  paperResult: (state) => {
    let wrongNum = 0
    const resultList = state.questionList.map((item) => {
      if (!["多选", "单选", "判断"].includes(item.type)) {
        return Object.assign(
          {
            isShowAnswer: true,
          },
          item
        )
      } else {
        let isWrong = false
        if (item.type === "多选") {
          isWrong = item.selectOption.join(",") !== item.right
        } else {
          isWrong = item.selectOption != item.right
        }
        isWrong && wrongNum++
        item["isWrong"] = isWrong
        const format = (item) => {
          let { selectOption, type, isWrong, right } = item
          let val = isWrong ? selectOption : right
          if (+val == -8 || val == undefined || val.length === 0) {
            return "未选择任何选项"
          } else if (type === "多选") {
            const letter = (val || [])
              .map((item) => {
                return { 1: "A", 2: "B", 3: "C", 4: "D" }[item]
              })
              .join(", ")
            return `你的选择是: ${letter}`
          } else if (type === "单选") {
            const letter = { 1: "A", 2: "B", 3: "C", 4: "D" }[+val]
            return `你的选择是: ${letter}`
          } else if (type === "判断") {
            const letter = { 1: "对", 2: "不对" }[+val]
            return `你的选择是: ${letter}`
          }
        }
        const answerIntro = format(item)

        return Object.assign(
          {
            answerIntro,
            isShowAnswer: true,
            isCollected: false,
            wrongSelectOption: isWrong ? String(item.selectOption) : "",
          },
          item
        )
      }
    })

    const score =
      100 * ((state.questionNum - wrongNum) / state.questionNum).toFixed(1)
    return {
      resultList,
      score,
    }
  },
}

const actions = {
  // 获取试卷题目
  async getQuestionList({ commit }, { paperId, current, size }) {
    const res = await wx.BaaS.invoke("getQuestionList", {
      paperId,
      current,
      size,
    })
    // 首次加载
    if (current == 0) {
      console.log(
        "🚀 ~ file: question.js ~ line 97 ~ getQuestionList ~ current",
        current
      )
      commit("SET_QUESTION_LIST", [...res.data])
    } else {
      commit("SET_QUESTION_LIST", [...state.questionList, ...res.data])
    }
    return res.data.length <= size
  },

  // 获取试卷题目数量
  async getQuestionNum({ commit }, { paperId }) {
    let Question = new wx.BaaS.TableObject("question")
    // 获取试卷列表
    let QuestionPaper = new wx.BaaS.TableObject("question_paper")
    let questionPaper = QuestionPaper.getWithoutData(paperId)
    let query = new wx.BaaS.Query()
    query.compare("paper", "=", questionPaper)

    let questionNum = await Question.setQuery(query).count()

    commit("SET_QUESTION_NUM", questionNum)
  },

  // 获取收藏题目
  async getCollectList({ commit }, paperId) {
    let QuestionCollect = new wx.BaaS.TableObject("question_collect")
    let query = new wx.BaaS.Query()

    // 查询指定试卷收藏题目
    if (paperId) {
      let QuestionPaper = new wx.BaaS.TableObject("question_paper")
      let questionPaper = QuestionPaper.getWithoutData(paperId)
      query.compare("paper", "=", questionPaper)
    }
    const res = await QuestionCollect.setQuery(query).expand("question").find()

    commit("SET_COLLECT_LIST", res.data.objects)
    return res.data.objects
  },

  // 设置收藏题目
  async onCollectQuestion({ commit, state }, { questionIndex, paperId }) {
    let questionList = state.questionList
    const canCollect = !questionList[questionIndex]["isCollected"]

    let QuestionCollect = new wx.BaaS.TableObject("question_collect")
    let QuestionPaper = new wx.BaaS.TableObject("question_paper")
    let Question = new wx.BaaS.TableObject("question")

    if (canCollect) {
      if (func.isEmpty(paperId)) return uni.showToast("缺少关联试卷")

      let questionPaper = QuestionPaper.getWithoutData(paperId)
      let question = Question.getWithoutData(questionList[questionIndex].id)
      let MyRecord = QuestionCollect.create()
      MyRecord.set({
        paper: questionPaper,
        question: question,
      })
      const res = await MyRecord.save()

      questionList[questionIndex] = Object.assign(questionList[questionIndex], {
        isCollected: true,
        collectId: res.data.id,
      })
      uni.showToast({ title: "收藏成功!" })
    } else {
      // 取消收藏
      QuestionCollect.delete(questionList[questionIndex]["collectId"])
      questionList[questionIndex] = Object.assign(questionList[questionIndex], {
        isCollected: false,
        collectId: null,
      })
      uni.showToast({ title: "已取消收藏!", icon: "none" })
    }

    commit("SET_QUESTION_LIST", questionList)
  },

  // 设置选择选项
  onSelectOption({ commit }, { id, type, selectIndex }) {
    const questionList = state.questionList
    let questionIndex = questionList.findIndex((item) => item.id === id)
    questionList[questionIndex]["selectOption"] = selectIndex

    uni.vibrateShort()
    commit("SET_QUESTION_LIST", questionList)
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions,
}
